import axios from 'axios';
import Toast from '@/utils/toast';
import qs from 'qs';

const instance = axios.create({
  // baseURL: 'http://222.240.233.71:8142/',
  timeout: 30000,
  headers: {
    Accept: 'application/json',
  },
  transformRequest: [function (data) {
    let src = ''
    for (let item in data) {
      src += encodeURIComponent(item) + '=' + encodeURIComponent(data[item]) + '&'
    }
    return src
  }]
});

//请求拦截处理
instance.interceptors.request.use(config => {
  // 如果config中有传token: true,自动添加token参数
  // 在发送请求之前做些什么
  return config;
}, error => {
  // 对请求错误做些什么
  Toast.error('网络异常')
  return Promise.reject(error);
});

//返回拦截处理
instance.interceptors.response.use(res => {
  if (res.data.code === 200) {
    
  }else{
    if(res.data.status==0){
      self.location.href="/login"
    }
    Toast.error(res.data.message)
  }
  // 对响应数据做点什么
  // if(res.data.code===0){
    
  // }
  return res;
}, error => {
  // 对响应错误做点什么
  Toast.error('网络异常')
  return Promise.reject(error);
});

export const Post = async (api, params, options) => {
  return new Promise((resolve, reject) => {
    instance.post(api, params, options)
    .then(res => {
      resolve(res.data)
    })
    .catch(error => {
      reject(error)
    })
  })
};

export const Get = async (api, params, options) => {
  return new Promise((resolve, reject) => {
    instance.get(api, { params }, options)
    .then(res => {
      resolve(res.data)
    })
    .catch(error => {
      reject(error)
    })
  })
};

export default {
  Get: Get,
  Post: Post,
}